<?php

namespace app\im\controller;
use app\ApiRest;
use app\Common\service\LongbingUserInfoService;
use app\im\model\ImMessageFriend;
use app\im\service\ImMessageFriendService;
use app\im\service\ImService;
use longbingcore\tools\LongbingDefault;
use longbingcore\tools\LongbingTime;
use think\App;
use think\Request;
use app\im\model\ImChart;
use app\im\model\ImChat;
use app\im\model\ImMessage;
use app\im\model\ImUser;
use app\im\model\ImMyReply;
use app\im\model\ImReplyType;
use app\card\model\UserInfo;
use app\card\model\UserPhone;
use app\im\model\ImClient;
class Im extends ApiRest
{
    public $user_id = null;
    public $user = null;
    public function __construct(App $app) {
        parent::__construct($app);
          $this->user_id = $this->getUserId();
          $this->user = $this->getUserInfo();
    }

    //获取客户列表
    public function listCustomer()
    {
        //获取参数列表
        $param = $this->_param;
        //获取用户列表
        $user_id = $this->user_id;
        //判断用户是否存在
        if(empty($user_id)) return $this->error('not login ,please login again.');


        //生成分页信息
        $page_config = array(
            'page' => 1,
            'page_count' => 10
        );
        //获取分页信息
        if(isset($param['page']) && $param['page'] > 0) $page_config['page'] = $param['page'];
        if(isset($param['page_count']) && $param['page_count'] > 0) $page_config['page_count'] = $param['page_count'];
        //生成查询模型
        $chat_model = new ImChat();
        //生成消息查询模型
        $message_model = new ImMessage();
        //生成用户查询模型
//        $user_model = new ImUser();
        //生成查询
        $page_config['total'] = $chat_model->listChatCount($user_id ,$this->_uniacid );
        $chats = $chat_model->listChat($user_id  ,$this->_uniacid ,$page_config);
        $data  = [];
        if(!empty($chats))
        {
            foreach($chats as $key => $value)
            {
                //获取客户信息
                $customer_id = null;
                if(!in_array($value['user_id'], [$user_id])) $customer_id = $value['user_id'];
                if(!in_array($value['target_id'], [$user_id])) $customer_id = $value['target_id'];
                if(empty($customer_id)) continue;
                //获取客户信息
//                $value['customer'] = $user_model->getUser(['id' => $customer_id]);
                $customer = longbingGetUser($customer_id ,$this->_uniacid);
                if(!empty($customer['is_staff']))
                {
                    $customer_info = longbingGetUserInfo($customer_id ,$this->_uniacid);
                    if(isset($customer_info['is_staff']) && !empty($customer_info['is_staff']))
                    {
                        if(!empty($customer_info['avatar'])) {
                            $customer_info = transImagesOne($customer_info ,['avatar'] ,$this->_uniacid);
                        }
                        //是员工 就用员工头像 By.jingshuixian
                        //if(!empty($customer_info['avatar'])) $customer['avatarUrl'] = $customer_info['avatar'];
                    }
                }
                $value['customer'] = $customer;
                if(empty($value['customer'])) continue;

                //获取最后一条消息
                $lastmessage = $message_model->lastMessage(['chat_id' => $value['id']]);
                //如果最后一条消息是图片
                if(isset($lastmessage['message_type']) && !in_array($lastmessage['message_type'], ['text' ])) $lastmessage['content'] = lang($lastmessage['message_type']);
                $value['lastmessage'] = $lastmessage;
                //获取未读消息总数
                $not_rear_message_count = $message_model->listMessageCount(['chat_id' => $value['id'] ,'user_id' => $customer_id ,'target_id' => $user_id ,'status' => 1]);

                //未读消息总数
                $value['not_read_message_count'] = $not_rear_message_count;
                //获取时间
                if(isset($value['update_time']) && !empty($value['update_time'])) $value['time'] = date('Y-m-d H:i:s', $value['update_time']);
                //判断用户是否存在头像
                if(!isset($value['customer']['avatarUrl']) || empty($value['customer']['avatarUrl'])) $value['customer']['avatarUrl'] = $this->defaultImage['avatar'];
                //判断客户是否是员工
                if(isset($value['customer']['is_staff']) && !empty($value['customer']['is_staff']))
                {
                    //获取员工信息
                    $user_info = longbingGetUserInfo($customer_id ,$this->_uniacid);
                    if(isset($user_info['is_staff']) && !empty($user_info['is_staff']) && isset($user_info['name']) && !empty($user_info['name'])){
                        $value['customer']['nickName'] = $user_info['name'];
                    }
                }
                $data[] = $value;
            }
        }
        $page_config['total_page'] = (int)($page_config['total'] / $page_config['page_count']);
        if(($page_config['total'] % $page_config['page_count']) > 0) $page_config['total_page'] = $page_config['total_page'] + 1;
        $result = $page_config;
        $result['data'] = $data;

        //总计未读数
        $result['unReadMessageCount'] = ImService::getUnReadMessageCount($this->user_id);

        //数据处理
        return $this->success($result);
    }

    /**
     * @author jingshuixian
     * @DataTime: 2020/1/16 15:58
     * @功能说明:新版获取用户列表信息
     */
    public function listCustomerV2(){

        //获取参数列表
        $param = $this->_param;
        //获取用户列表
        $user_id = $this->user_id;
        //判断用户是否存在
        if(empty($user_id)) return $this->error('not login ,please login again.');
        //初始化朋友列表，兼容老数据
        ImMessageFriendService::initOldFriendList($this->_uniacid , $user_id) ;

        $result = ImMessageFriendService::getFriendList($this->_uniacid , $user_id , $param['page_count'] ) ;
        //总计未读数
        $result['unReadMessageCount'] = ImService::getUnReadMessageCount($this->user_id);
        //数据处理
        return $this->success($result);


    }

    //获取未读消息列表
    public function listNotReadMessage()
    {
        //获取参数
        $param = $this->_param;
        $user_id = $this->user_id;
        if(!isset($param['chat_id'])  || !isset($param['target_id'])) return $this->error(lang('not chat id ,please check param'));
        if(isset($param['target_id']) && !isset($param['chat_id']) && !empty($param['target_id']))
        {
            //获取chat数据
            $chat = longbingGetChat($user_id ,$param['target_id'] ,$this->_uniacid);
            if(isset($chat['id'])) $param['chat_id'] = $chat['id'];
        }
        //判断chat_id参数是否存在
        if(!isset($param['chat_id'])) return $this->error('not chat id ,please check param');
        //if(!isset($param['user_id'])) return $this->error('not user id ,please check param');
        $chat_id = $param['chat_id'];
        //获取客户关系
        $chat = longbingGetChatById($chat_id ,$this->_uniacid);
        //判断数据是否存在
        if(empty($chat)) return $this->error('not the chat ,please check chat id');
        $customer_id = $chat['user_id'];
        if(in_array($customer_id, [$this->user_id])) $customer_id = $chat['target_id'];
        $user_id  = $this->user_id;
        //生成查询模型
        $message_model = new ImMessage();
        //查询数据
        $messages = $message_model->listNotReadMessage(['chat_id' => $chat_id ,'target_id' => $user_id]);

        $result['data'] = [];
        if(!empty($page_config['total'])){
            foreach($messages as $key => $val)
            {
                if(isset($val['create_time']) && !empty($val['create_time'])) $val['time'] = date('Y-m-d H:i:s', $val['create_time']);
                $result['data'][]  = $val;
            }

        }
        if(isset($this->user['qr_path'])) $this->user = transImagesOne ( $this->user, ['qr_path'] );
        $result['user'] = $this->user;
        $customer = getUser($customer_id ,$this->_uniacid);


        if(isset($customer['qr_path'])) $customer = transImagesOne ( $customer, ['qr_path'] );
        $result['customer'] = $customer;
        return $this->success($result);
    }

    //获取消息列表
    public function listMessage()
    {
        $user = longbingGetUser($this->user_id ,$this->_uniacid);
        //获取参数
        $param      = $this->_param;
        $chat_id    = null;
        $customer_id = null;
        $chat         = null;
        //判断参数是否存在
        if(isset($param['chat_id'])) $chat_id = $param['chat_id'];
        if(isset($param['customer_id'])) $customer_id = $param['customer_id'];
        if(empty($chat_id) && empty($customer_id)) $this->error(lang('not customer id,please check param'));
        //参数处理(兼容处理)
        $result = [];
        if(!empty($chat_id))
        {
            $chat  = longbingGetChatById($chat_id ,$this->_uniacid);
        }
        else{
            $chat  = longbingGetChat($this->user_id ,$customer_id ,$this->_uniacid ,true);
        }
        //生成分页信息
        $page_config = array(
            'page' => 1,
            'page_count' => 20
        );


        //获取分页信息
        if(isset($param['page']) && $param['page'] > 0) $page_config['page'] = $param['page'];
        if(isset($param['page_count']) && $param['page_count'] > 0) $page_config['page_count'] = $param['page_count'];
        if(!empty($chat))
        {
            $customer_id = $chat['user_id'];
            if(empty($chat_id)) $chat_id = $chat['chat_id'];
            if(in_array($customer_id, [$this->user_id])) $customer_id = $chat['target_id'];
            //生成消息查询模型
            $message_model = new ImMessage();
            //获取查询总数
            $page_config['total'] = $message_model->listMessageCount(['chat_id' => $chat_id]);
            //生成分页数据
            $page_config['total_page'] = (int)($page_config['total'] / $page_config['page_count']);
            if(($page_config['total'] % $page_config['page_count']) > 0) $page_config['total_page'] = $page_config['total_page'] + 1;
            //生成返回数据
        }else{
            $page_config['total'] = 0;
            $page_config['total_page'] = 0;
        }
        $result  = $page_config;
        $result['data'] = [];
        //获取客户信息
        $customer = longbingGetUser($customer_id ,$this->_uniacid);
        if(empty($customer)) return $this->error(lang('user not exist.'));
        //获取头像
        if(isset($customer['avatarUrl'])) {
            $customer = transImagesOne ( $customer, ['avatarUrl'] ,$this->_uniacid);
        }else{
            $customer['avatarUrl'] = $this->defaultImage['avatarUrl'];
        }
        //判断客户是否是员工
        if(!empty($customer['is_staff']))
        {
            $customer_info = longbingGetUserInfo($customer_id ,$this->_uniacid);
            if(isset($customer_info['is_staff']) && !empty($customer_info['is_staff']))
            {
                if(!empty($customer_info['avatar'])) {
                    $customer_info = transImagesOne($customer_info ,['avatar'] ,$this->_uniacid);
                }
                if(!empty($customer_info['avatar'])) $customer['avatarUrl'] = $customer_info['avatar'];
            }
        }
        //获取客户电话号码和微信号码
        $customer['wechat'] = null;
        $phone = null;
        $user_info_model = new UserInfo();
        //获取微信和电话号码
        $user_info = $user_info_model->getUserPhone($customer_id ,$this->_uniacid);
        if(isset($user_info['phone']) && !empty($user_info['phone'])) $phone = $user_info['phone'];
        if(isset($user_info['wechat']) && !empty($user_info['wechat'])) $customer['wechat'] = $user_info['wechat'];
        if(empty($phone)){
            $user_phone_model = new UserPhone();
            $user_phone = $user_phone_model->getUserPhone($customer_id ,$this->_uniacid);
            if(isset($user_phone['phone']) && !empty($user_phone['phone'])) $phone = $user_phone['phone'];
        }
        //判断聊天者是否是客户
        $customer['is_customer'] = false;
        $collection_model = new ImClient();
        if(!empty($collection_model->isCustomer($this->user_id , $customer_id ,$this->_uniacid))) $customer['is_customer'] = true;
        //判断客户是否是员工
        if(isset($customer['is_staff']) && !empty($customer['is_staff']))
        {
            $customer_info = longbingGetUserInfo($customer_id ,$this->_uniacid);
            if(isset($customer_info['is_staff']) && !empty($customer_info['is_staff']) && isset($customer_info['name']) && !empty($customer_info['name'])){
                $customer['nickName'] = $customer_info['name'];
                //生成第一条默认返回数据
                $result['data'][] = array(
                                        'chat_id'      => $chat['id'],
                                        'user_id'      => $customer_id,
                                        'target_id'    => $this->user_id,
                                        'status'       => 2,
                                        'uniacid'      => $this->_uniacid,
                                        'message_type' => 'welcome',
                                        'content'      => lang('Hello, I am ') . $customer['nickName'] . lang(', May I help you? Please contact me!')
                                    );
            }
        }
        $customer['phone'] = $phone;

        if(!empty($page_config['total'])){

            $msgwhere[] = ['chat_id','=',$chat_id];
            //自己发送的
            $msgwhere[] = ['is_show','<>',2];

            $msgwhere[] = ['user_id','=',$this->getUserId()];

            $msgwhere[] = ['deleted','=',0];

            $whereT[] = ['deleted','=',0];
            //自己接受的
            $whereT[] = ['target_id','=',$this->getUserId()];

            $whereT[] = ['target_is_show','<>',2];

            $whereT[] = ['chat_id','=',$chat_id];

            foreach($message_model->listMessageV2($msgwhere ,$page_config,$whereT) as $key => $val)
            {
                if(isset($val['create_time']) && !empty($val['create_time'])) $val['time'] = date('Y-m-d H:i:s', $val['create_time']);
                $result['data'][]  = $val;
            }

            //dump($this->getUserId(),$chat['user_id'],$msgwhere,$result['data']);exit;

        }
//      if(isset($this->user['qr_path'])) $this->user = transImagesOne ( $this->user, ['qr_path'] );

        //判断用户是否是员工
        if(!empty($user['is_staff']))
        {
            $user_info = longbingGetUserInfo($this->user_id ,$this->_uniacid);
            if(isset($user_info['is_staff']) && !empty($user_info['is_staff']))
            {
                if(!empty($user_info['avatar'])) {
                    $user_info = transImagesOne($user_info ,['avatar'] ,$this->_uniacid);
                }
                if(!empty($user_info['avatar'])) $user['avatarUrl'] = $user_info['avatar'];
            }
        }

        //默认头像处理

        //没有头像就给一个默认头像
        $customer['avatarUrl'] = empty($customer['avatarUrl']) ?  LongbingDefault::$avatarImgUrl  : $customer['avatarUrl'];
        $user['avatarUrl'] = empty($user['avatarUrl']) ?  LongbingDefault::$avatarImgUrl  : $user['avatarUrl'];

        $result['user'] = $user;

        $result['customer'] = $customer;
        //阅读所有消息
        $result['readMessageNumber'] = ImService::readMessage($this->_uniacid ,$this->user_id  , $customer_id);


        return $this->success($result);
    }

    //标记已读消息
    public function readMessage()
    {
        $param = $this->_param ;
        $message_model = new ImMessage();
        $count = 0 ;
        if ( isset($param['id'])  ) {
            $id =  $param['id'] ;
            $message = $message_model->find($id);
            if($message){
                ImService::readMessage($this->_uniacid ,$this->user_id , $message['user_id'] ) ;
            }

        }

        return $this->success(['count' => $count ] );

    }

    //获取常用话术
    public function listReply()
    {
        //获取用户信息
        $user_id = $this->user_id;
        //生成话术分类查询模型
        $reply_type_model = new ImReplyType();
        //生成快速回复话术查询模型
        $reply_model     = new ImMyReply();
        //获取自定义话术
        $my_replys     = $reply_model->listReply(['uniacid' => $this->_uniacid ,'user_id' => $user_id ,'status' => 1]);
        $result[] = ['title' => lang('my reply') , 'data' => $my_replys ,'is_myself' => true];
        //获取types
        $types = $reply_type_model->listAllType(['uniacid' => $this->_uniacid ,'status' => 1]);
        foreach($types as $type)
        {
            $data['title'] = $type['title'];
            $data['data']  = $reply_model->listReply(['uniacid' => $this->_uniacid ,'user_id' => 0 ,'status' => 1 ,'type' => $type['id']]);
            $data['is_myself']    = false;
            $result[] = $data;
        }
        return $this->success($result);
    }

    //创建和更新常用话术
    public function addReply()
    {
        //获取参数
        $input = $this->_input;
        $param = $this->_param;
        if(!isset($input['content'])) return $this->error('content is not exist ,please check .');
        $is_create = true;
        if(isset($input['id']) && !empty($input['id'])) $is_create = false;
        //获取用户信息
        $user_id = $this->user_id;
        //生成快速回复话术查询模型
        $my_reply_model = new ImMyReply();
        if($is_create)
        {
            //创建
            $result = $my_reply_model->createReply(['uniacid' => $this->_uniacid ,'status' => 1 ,'content' => $input['content'] ,'user_id' => $user_id]);
        }else{
            //修改
            $result = $my_reply_model->updateReply(['id' =>$param['id'] , 'uniacid' => $this->_uniacid ,'user_id' => $user_id] ,['content' => $input['content']]);
        }

        //获取自定义话术
        return $this->success($result);
    }

    //删除常用话术
    public function delReply()
    {
        $param   = $this->_param;
        $user_id = $this->user_id;
        if(!isset($param['id'])) return $this->error('reoly id is not exist ,please check .');
        //生成快速回复话术查询模型
        $my_reply_model = new ImMyReply();
        //删除话术
        $result  = $my_reply_model->deleteReply(['id' =>$param['id'] ,'uniacid' => $this->_uniacid  ,'user_id' => $user_id]);

        return $this->success($result);

    }

    /**
     * 腾讯IM签名
     *
     * @author shuixian
     * @DataTime: 2019/12/10 11:30
     */
    public function getTimUserSig(){
        //需要远程获取和加密
        $sdkappid = 1400288706 ;
        $key  = 'd31548b81e57bf823e12d240e4cce237e09f666bdff3fc325eb4bc386e62832d' ;
        $user_id = $this->_param['user_id'];
        $userSig =  longbing_publics_tim_genSig($sdkappid , $key , $user_id );

        $result = ['user_id'=>$user_id , 'userSig' => $userSig] ;

        return $this->success($result);
    }


    /**
     * 保存聊天信息
     *
     * @return \think\Response
     * @author shuixian
     * @DataTime: 2019/12/11 9:29
     */
    public function sendMessage(){
        //获取参数列表

        //{type: "text", content: "456789", target_id: 14, uniacid: "8890", user_id: 20}  //发消息
        //{"action":"getUnReadMessageCount","status":true,"message":"","data":{"count":2}} // 获取未读消息树
        $param = $this->_param;

        //获取房间ID

        $chat_id =  ImService::getChatId($this->_uniacid , $this->user_id, $param['target_id']);
        //还需要校验参数合法新

        $value['message_type']    = $param['message_type'];
        $value['chat_id']         = $chat_id;//需要获取和判断
        $value['user_id']         = $this->user_id;
        $value['target_id']       = $param['target_id'];  //需要判断接收用户的合法性
        $value['content']         = $param['content'];
        $value['status']          = 1;
        $value['uniacid']         = $this->_uniacid;
        $value['create_time']     = time();
        $value['update_time']     = time();
        $value['is_show']         = 1;

        $result = ImService::addMessage($value);

        if($result){
            $value['id'] = $result ;

            ImService::sendImMessageTmpl($this->_uniacid , $value['user_id'] , $value['target_id']) ;


            return $this->success( $value );
        }else{
            $this->error('');
        }

    }


    /**
     * @author jingshuixian
     * @DataTime: 2020/1/15 13:13
     * @功能说明:获取目标客户发送的消息数量
     */
    public function getCustomerUnReadMessageCount(){


        $param   = $this->_param ;

        $user_id = $this->user_id;

        $target_id = 0 ;

        $count     = 0 ;

        if (isset($param['target_id'])) {

            $target_id = $param['target_id'];

            $count = ImService::getUnReadMessageCountByUserIdAndTargetId( $target_id ,  $user_id);

        }

        $data[] = ['action'=> 'getCustomerUnReadMessageCount' , 'data' => ['count' => $count,  'user_id' =>  $user_id  , 'target_id' =>  $target_id ]  ]  ;

        $data[] = ['action' => 'getUnReadMessageCount' , 'data' => ['count' => ImService::getUnReadMessageCount($user_id) ]  ]  ;

        $message_model = new ImMessage();

        $messageList =  $message_model->where(  [ ['user_id' , '=' ,$target_id ]  ,[ 'target_id' , '=' , $user_id ] , ['status', '=' , 1]] )->select();

        foreach ($messageList as $item ){

            $data[] = ['action' => 'getNewMessage'  , 'data' =>  $item ] ;
        }

        $key  = 'message'.$user_id.'-'.$target_id;
        //获取撤回消息
        $cancel_msg = getCache($key,$this->_uniacid);

        $data[] = ['action' => 'getCancelMessage'  , 'data' =>  $cancel_msg ] ;

        setCache($key,[],0,$this->_uniacid);

        return $this->success( $data ) ;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-05-26 17:33
     * @功能说明:修改消息状态 1都可见 2删除对方可见 撤回都不可见
     */
    public function updateMsgStatus(){

        $input  = $this->_input;

        $message_model = new ImMessage();

        $info = $message_model->where(['id'=>$input['id']])->find()->toArray();
        //撤回只有送人课操作
        if($input['is_show']==-1){

            $update['is_show'] = -1;

            if($info['target_is_show']==1){

                $update['target_is_show'] = -1;
            }

        }
        //删除
        if($input['is_show']==2){
            //判断我是否是发送者
            if($info['user_id']==$this->getUserId()){

                $update['is_show'] = 2;

            }else{

                $update['target_is_show'] = 2;

            }

        }

        $res  = $message_model->where(['id'=>$input['id']])->update($update);

        $data = $message_model->where(['id'=>$input['id']])->find();

        if(!empty($data)){

            $data = $data->toArray();

            $key  = 'message'.$data['target_id'].'-'.$data['user_id'];

            setCache($key,$data,0,$this->_uniacid);

        }

        return $this->success( $res ) ;


    }



}